package com.azzcs.customer.interceptor;

import com.azzcs.customer.config.Security;
import com.azzcs.mvc.servlet.HandlerInterceptor;
import com.azzcs.mvc.servlet.HandlerMethod;
import com.azzcs.spring.anno.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: wzg
 * @Date: 2020/12/29 上午11:09
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Class<?> beanType = handlerMethod.getBeanType();
            Security classSecurity = beanType.getAnnotation(Security.class);
            List<String> users = new ArrayList<>();
            addUsers(users,classSecurity);
            Method method = handlerMethod.getMethod();
            Security methodSecurity = method.getAnnotation(Security.class);
            addUsers(users,methodSecurity);
            boolean status = checkUsers(users, req);
            if(!checkUsers(users,req)){
                responseNoPermission(resp);
            }
            return status;
        }
        return true;
    }

    private void responseNoPermission(HttpServletResponse resp) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = null;
        try {
            printWriter = resp.getWriter();
            printWriter.println("没有访问权限");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean checkUsers(List<String> users, HttpServletRequest req) {
        String username = req.getParameter("username");
        if(users.size() == 0){
            return true;
        }
        return users.contains(username);
    }

    private void addUsers(List<String> users, Security security) {
        if(security != null) {
            String[] classUsers = security.value();
            if(classUsers != null && classUsers.length > 0){
                List<String> list = Arrays.asList(classUsers);
                users.addAll(list);
            }
        }
    }
}
